package cn.bocweb.spinning.view.forun;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.BindColor;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.ForunGetCatBean;
import cn.bocweb.spinning.model.Bean.ForunSendBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.adapter.GvImgAdapter;
import cn.bocweb.spinning.view.common.BaseActivity;
import cn.bocweb.spinning.view.common.ContainsEmojiEditText;
import de.greenrobot.event.EventBus;
import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.utils.PhotoPickerIntent;

public class ForunSendTopicActivity extends BaseActivity {

    ForunSelectCateDialog mForunSelectCateDialog;
    List<ForunGetCatBean.DataBean> list;
    UserPresenter presenter;
    String userid;
    String cat;
    List<File> files;
    GvImgAdapter mGvImgAdapter;
    int photo_size = 3;
    int photoCount;


    @BindColor(R.color.white)
    int white;
    @Bind(R.id.submit)
    TextView mSubmit;
    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @Bind(R.id.title)
    ContainsEmojiEditText mTitle;
    @Bind(R.id.content)
    ContainsEmojiEditText mContent;
    @Bind(R.id.btn_photo)
    ImageView mBtnPhoto;
    @Bind(R.id.select_cate)
    TextView mSelectCate;
    @Bind(R.id.gv_img)
    RecyclerView mGvImg;
    @Bind(R.id.img_count)
    TextView mImgCount;
    @Bind(R.id.add_image)
    RelativeLayout mAddImage;
    @Bind(R.id.tv_content_count)
    TextView mTvContentCount;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forun_send_topic);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        files = new ArrayList<>();
        mGvImgAdapter = new GvImgAdapter(files);
        mForunSelectCateDialog = new ForunSelectCateDialog(this);
        presenter = new UserPresenterImp();
        UserBean.DataEntity d = new UserBean.DataEntity();
        d.readInfoFromLocal(this);
        userid = d.getUserid();

        initToolbar();
        initImgList();
        presenter.forunGetCate();

        mContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                mTvContentCount.setText(String.valueOf(s.toString().length()));
            }
        });

        mGvImgAdapter.setOnItemClickListener(new GvImgAdapter.OnItemClickListener() {
            @Override
            public void onClick() {
                if (Build.VERSION.SDK_INT >= 23) {
                    int camarePermission = ContextCompat.checkSelfPermission(ForunSendTopicActivity.this, Manifest.permission.CAMERA);
                    int photoPermission = ContextCompat.checkSelfPermission(ForunSendTopicActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE);
                    if (camarePermission != PackageManager.PERMISSION_GRANTED || photoPermission != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(
                                ForunSendTopicActivity.this,
                                new String[]{
                                        Manifest.permission.CAMERA,
                                        Manifest.permission.READ_EXTERNAL_STORAGE}, 301);
                        return;
                    }
                }
                PhotoPickerIntent intent = new PhotoPickerIntent(ForunSendTopicActivity.this);
                intent.setPhotoCount(3 - photoCount);
                intent.setShowCamera(true);
                intent.setShowGif(true);
                startActivityForResult(intent, Constant.FORUN_SEND_PIC);
            }
        });
    }


    @Override
    protected void onRestart() {
        super.onRestart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constant.FORUN_SEND_PIC) {
            if (data != null) {
                ArrayList<String> photos = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
                if (photos.isEmpty()) {
                    mImgCount.setVisibility(View.GONE);
                } else {
                    mImgCount.setVisibility(View.VISIBLE);
                    mGvImg.setVisibility(View.VISIBLE);
                    for (String filePath : photos) {
                        File file = new File(filePath);
                        files.add(file);
                    }
                    photo_size = 3 - files.size();
                    photoCount = files.size();
                    mImgCount.setText(String.valueOf(files.size()));
                    if (files.size() == 3) {
                        mAddImage.setVisibility(View.GONE);
                    } else {
                        mAddImage.setVisibility(View.VISIBLE);
                    }
                    mGvImgAdapter.notifyDataSetChanged();
                    mGvImgAdapter.setOnImgDeleteListener(new GvImgAdapter.OnImgDeleteListener() {
                        @Override
                        public void onclick(int position) {
                            files.remove(position);
                            photoCount = files.size();
                            photo_size ++;
                            mAddImage.setVisibility(View.GONE);
                            mImgCount.setText(String.valueOf(files.size()));
                            mGvImgAdapter.notifyDataSetChanged();
                            if (!files.isEmpty()) {
                                mImgCount.setVisibility(View.VISIBLE);
                            } else {
                                mImgCount.setVisibility(View.GONE);
                            }
                        }
                    });
                }
            }
        }
    }

    /**
     * 网络回调
     */

    public void onEventMainThread(ForunGetCatBean bean) {
        if (bean.getReturn_code() == 0) {
            DeviceUtil.Log(bean.getMsg());
            mForunSelectCateDialog.setForun(bean.getData());
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }

    public void onEventMainThread(ForunSendBean bean) {
        DeviceUtil.MyToast(this, bean.getMsg());
        hideLoading();
        if (bean.getReturn_code() == 0) {
            finish();
        }
    }

    private void initImgList() {
        GridLayoutManager manager = new GridLayoutManager(this, 3);
        mGvImg.setLayoutManager(manager);
        mGvImg.setAdapter(mGvImgAdapter);
    }

    private void initToolbar() {
        mToolbar.setTitle("发表话题");
        mToolbar.setTitleTextColor(white);
        mToolbar.setNavigationIcon(R.mipmap.btn_exit);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 301: {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    PhotoPickerIntent intent = new PhotoPickerIntent(ForunSendTopicActivity.this);
                    intent.setPhotoCount(3 - photoCount);
                    intent.setShowCamera(true);
                    intent.setShowGif(true);
                    startActivityForResult(intent, Constant.FORUN_SEND_PIC);
                } else {
                    DeviceUtil.MyToast(ForunSendTopicActivity.this, "未获得相应权限");
                }
            }
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @OnClick({R.id.submit, R.id.select_cate, R.id.add_image})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.submit:
                if (TextUtils.isEmpty(cat)) {
                    DeviceUtil.MyToast(this, "请选择社区");
                } else {
                    presenter.sendForun(userid, cat, mTitle.getText().toString(), mContent.getText().toString(), files);
                    mSubmit.setClickable(false);
                    showLoading();
                }
                break;
            case R.id.select_cate:
                mForunSelectCateDialog.show();
                break;
            case R.id.add_image:
                if (Build.VERSION.SDK_INT >= 23) {
                    int camarePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
                    int photoPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
                    if (camarePermission != PackageManager.PERMISSION_GRANTED || photoPermission != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(
                                this,
                                new String[]{
                                        Manifest.permission.CAMERA,
                                        Manifest.permission.READ_EXTERNAL_STORAGE}, 301);
                        break;
                    }
                }
                PhotoPickerIntent intent = new PhotoPickerIntent(ForunSendTopicActivity.this);
                intent.setPhotoCount(3 - photoCount);
                intent.setShowCamera(true);
                intent.setShowGif(true);
                startActivityForResult(intent, Constant.FORUN_SEND_PIC);
                break;
        }
    }

    public void setCat(String cat, String cat_name) {
        this.cat = cat;
        mSelectCate.setText(cat_name);
    }
}
